package base

import (
	"context"
	"reflect"

	"github.com/liyaozong/mengo/common/di"
	"github.com/liyaozong/mengo/core/base/container"
	"github.com/liyaozong/mengo/core/device/config"
	"github.com/spf13/viper"

	"github.com/liyaozong/mengo/contracts/common"

	"github.com/liyaozong/mengo/core/base/handlers"
	"github.com/liyaozong/mengo/core/base/interfaces"
)

func Main(ctx context.Context, cancel context.CancelFunc) {
	// 配置初始化
	configServer := handlers.NewConfigServer(viper.New())

	// 加载配置
	configuration := configServer.LoadConfig(reflect.TypeOf(config.ConfigurationStruct{}))
	dic := di.NewContainer(di.ServiceConstructorMap{
		container.ConfigurationInterfaceName: func(get di.Get) interface{} {
			return configuration
		},
	})

	// 初始化Router
	router := NewBootstrap(common.CoreDeviceServiceKey)

	// 执行启动流程
	Run(
		ctx,
		cancel,
		common.CoreDeviceServiceKey,
		configuration,
		dic,
		true,
		[]interfaces.BootstrapHandler{
			handlers.NewDatabase(ctx, configuration).BootstrapHandler, // 数据库客户端启动处理
			// handlers.MessagingBootstrapHandler,                    // 消息处理的启动
			// handlers.NewServiceMetrics(common.CoreMetaDataServiceKey).BootstrapHandler, // 服务指标收集的启动，必须在消息处理之后
			// handlers.NewStartMessage(common.CoreMetaDataServiceKey, men.Version).BootstrapHandler, // 发送启动消息
			router.BootstrapHandler, // http的启动处理
		},
	)

	lc := container.LoggingClientFrom(dic.Get)
	lc.Info("Server is running")

	router.Run(configuration.GetListenAddr())
}
